# coding:utf-8
from . import models
from rest_framework import serializers
import re
from rest_framework.exceptions import ValidationError
from django.core.cache import cache
from django.conf import settings

class UserSerializer(serializers.ModelSerializer):
    username = serializers.CharField( )
    class Meta:
        model = models.UserInfo
        fields = ['username', 'password']

    def validate(self, attrs):
        #多种登录方式
        user = self._get_user(attrs)
        #签发token
        token = self._get_token(user)
        #放到context中，我在视图类中可以取出来
        self.context['token'] = token
        self.context['user'] = user
        return attrs


    def _get_user(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        # 用户名有三种方式：手机号、邮箱、密码
        # 1 手机号匹配
        if re.match('^1[3-9][0-9]{9}$', username):
            user = models.UserInfo.objects.filter(telephone=username).first()
        # 2 邮箱匹配
        elif re.match('^.+@.+$', username):
            user = models.UserInfo.objects.filter(email=username).first()
        # 3 用户名匹配
        else:
            user = models.UserInfo.objects.filter(username=username).first()
        if user:
            if user.check_password(password):
               return user
            else:
                raise ValidationError('密码错误')
        else:
            raise ValidationError('用户名不存在')

    def _get_token(self, user):
        from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return token


#验证码登录
class CodeUserSerializer(serializers.ModelSerializer):
    code = serializers.CharField()
    class Meta:
        model = models.UserInfo
        fields = ['telephone', 'code']
    def validate(self, attrs):
        #1 判断用户是否存在
        user = self._get_user(attrs)
        #2 如果用户存在则签发token
        token = self._get_token(user)
        self.context['token'] = token
        self.context['user'] = user
        return attrs

    #获取用户
    def _get_user(self, attrs):
        telephone = attrs.get('telephone')
        code = attrs.get('code')
        if re.match('^1[3-9][0-9]{9}$', telephone):
            #取出缓存的code
            cache_code = cache.get(settings.PHONE_CACHE_KEY % telephone)
            print("cache_code",cache_code)
            #验证码相同时
            if code == cache_code:
            # if code == "111111":
                user = models.UserInfo.objects.filter(telephone=telephone).first()
                if user:
                    #1)删除缓存中的验证码
                    # cache.set(settings.PHONE_CACHE_KEY%telephone, '')
                    del cache[settings.PHONE_CACHE_KEY%telephone]
                    #2）返回 user
                    return user
                else:
                    raise ValidationError('用户不存在')
            else:
                raise ValidationError('验证码不正确')
        else:
            raise ValidationError('手机号不合法')
    #获取token
    def _get_token(self, user):
        from rest_framework_jwt.serializers import jwt_payload_handler,jwt_encode_handler
        payload = jwt_payload_handler(user)  #通过user对象获得payload
        token = jwt_encode_handler(payload)  #通过 payload 获得token
        return token



#验证码注册
class RegisterSerializer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    class Meta:
        model = models.UserInfo
        fields = ['telephone', 'code', 'password', 'username']
        extra_kwargs= {
            'password':{'max_length':18, 'min_length':6},
            'username':{'read_only':True}
        }
    def validate(self, attrs):
        telephone = attrs.get('telephone')
        code = attrs.get('code')
        print(code)
        #判断手机是否合法
        if re.match('^1[3-9][0-9]{9}$', telephone):
            #取出缓存中的验证码进行对比
            cache_code = cache.get(settings.PHONE_CACHE_KEY%telephone)
            print("cache_code", cache_code)
            if code == cache_code:
                #验证码通过时,把用户的名字设成手机号
                attrs['username'] = telephone
                attrs.pop('code')
                return attrs
            else:
                raise ValidationError('验证码不正确')
        else:
            raise ValidationError('手机号错误')

    #因为需要创建密文密码，所以需要重写create 方法
    def create(self, validated_data): #这里的validata_data就是全局校验返回的 attrs
        user = models.UserInfo.objects.create_user(**validated_data)
        return user




#密码注册
# class RegisterSerializer(serializers.ModelSerializer):
#     re_password = serializers.CharField(max_length=16, required=True, write_only=True)
#     class Meta:
#         model = models.UserInfo
#         fields = ['username', 'password', 're_password', 'telephone']
#         extra_kwargs = {
#             'password':{'write_only':True}
#         }
#     #局部钩子
#     def validate_telephone(self, data):
#         if not len(data)==11:
#             raise ValidationError('手机号不合法')
#         return data
#     #全局钩子
#     def validate(self, attrs):
#         if not attrs.get('re_password')== attrs.get('password'):
#             raise ValidationError('两次密码不一致')
#         attrs.pop('re_password')  #方便后面创建用户使用
#         return attrs
#
#     #因为需要创建密文密码，原生的序列化器中create方法创建的是明文
#     def create(self, validated_data):
#         user = models.UserInfo.objects.create_user(**validated_data)
#         return user


